import * as React from 'react'
import { QueryObserver, useQueryClient } from '@tanstack/react-query'
import { ITimeRef } from '../types';

// 缓存数据监听
export const useObserverData = (queryKey: Array<string | number>, setData: React.Dispatch<React.SetStateAction<any>>) => {
  const queryClient = useQueryClient()
  React.useEffect(() => {
    const observer = new QueryObserver(queryClient, {
      queryKey,
      staleTime: 1000 * 60 * 10, // 10分钟
      initialData: () => queryClient.getQueryData(queryKey),
    })
    return observer.subscribe((res: any) => setData(res.data))
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
}

// 滚动
export const useScroll = (timeRef: React.RefObject<ITimeRef>, containerRef: React.RefObject<HTMLDivElement>) => {
  React.useEffect(() => {
    ;(timeRef.current as ITimeRef).timer = setInterval(() => {
      if (containerRef.current) {
        const chilrenDiv = containerRef.current.children[0] as HTMLDivElement
        const pHeight = containerRef.current.offsetHeight
        const cHeight = chilrenDiv.offsetHeight

        if (cHeight - pHeight > 0) {
          if (containerRef.current.children.length < 2) {
            // 克隆一份子节点追加到父节点中
            containerRef.current.appendChild(chilrenDiv.cloneNode(true))
          }

          // 滚动到底部
          const bottom = cHeight * 2 - pHeight
          let span = timeRef.current?.span || 0

          if (!timeRef.current?.mouseEnter) {
            span += 1
            ;(timeRef.current as ITimeRef).span = span
          }
          if (span <= bottom && !timeRef.current?.mouseEnter) {
            if (span > cHeight) {
              span = 0
              ;(timeRef.current as ITimeRef).span = span
            }
            for (let i = 0; i < containerRef.current.children.length; i += 1) {
              const element = containerRef.current.children[i] as HTMLDivElement
              element.style.transform = `translateY(-${span}px)`
            }
          }
        }
      }
    }, 30)

    // eslint-disable-next-line react-hooks/exhaustive-deps
    return () => clearInterval((timeRef.current as ITimeRef).timer)
  }, [containerRef, timeRef])
}
